1. 使用React.createClass

    1
    onChange = { this.handleChange }

    在createClass内this会自动绑定到组件的实例上, 但是随着ES6 class的出现, 这种方法不被推荐

  2. 在render内bind

    1
    onChange = {this.handleChange.bind(this)}

    这个方法的缺陷在于函数在每次render都会被重新创建, 所以会有一定的性能影响, 当然, 这种影响在大多数的程序中并不会特别大, 但是如果程序有了性能需求, 这也是一个可以优化的点

  3. 在render内使用箭头函数

    1
    onChange = {e => this.handleChange(e)}

    这种方法和第二种方法有同样的性能缺陷

  4. 在constructor内进行绑定

    1
    2
    3
    4
    constructor(props){
    super(props)
    this.handleChange = this.handleChange.bind(this)
    }

    这是React doc里建议的一种提高React性能的办法, 但是由于2, 3在大部分程序中的性能影响并不明显, 而且需要写更多的代码, 于我个人来说并不愿意用他, 当一个Component内有较多的方法需要绑定时, 需要多写的代码看起来会很繁琐

  5. 在class的属性中使用箭头函数

    1
    2
    3
    4
    5
    6
    7
    handleChange = (e) => {
    console.log(e)
    }

    render(){
    return <div onChange = {this.handleChange}>hello world</div>
    }

    这种方法的优点在于避免了2, 3方法性能消耗的同时写法又不像4那么繁琐, 不算缺点的特点在于需要传参时比较尴尬, 可以通过data-*来进行传参, 个人使用最多的方法